package tool.zyk.protocol;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * author: zyk
 * datetime: 2024/1/27 10:08
 * describe:
 */
@Slf4j
public class ProtocolServer {
    public static void main(String[] args) {
        NioEventLoopGroup bossEventGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerEventGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            ChannelFuture channelFuture = serverBootstrap.channel(NioServerSocketChannel.class)
                    .group(bossEventGroup, workerEventGroup)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    log.info("connected :{}", ctx.channel());
                                    super.channelActive(ctx);
                                }

                                @Override
                                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                    log.info("disconnected :{}", ctx.channel());
                                    super.channelInactive(ctx);
                                }
                            });
                        }
                    }).bind(8089);

            Channel channel = channelFuture.channel();
            log.info("binding...{}", channel);
            channelFuture.sync();
            log.info("bound...{}", channelFuture.channel());

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            bossEventGroup.shutdownGracefully();
            workerEventGroup.shutdownGracefully();
        }


    }
}
